<?php

namespace app\common\http;
use GuzzleHttp\Client;
use support\Log;

class WXService
{
    protected static Client $client;

    public static function getClient (): Client
    {
        if (!isset(self::$client)) {
            self::$client = new Client([
                'base_uri' => 'https://api.weixin.qq.com',
                'timeout'  => 5.0,
            ]);
        }
        return self::$client;
    }

    public static function login($code)
    {
        Log::debug('收到前端 code', ['code' => $code]);

        $client = self::getClient();
        $response =  $client->get('/sns/jscode2session', [
            'query' => [
                'appid'      => config('helper.app.wx_app_id'),
                'secret'     => config('helper.app.wx_app_secret'),
                'js_code'    => $code,
                'grant_type' => 'authorization_code',
            ],
        ]);

        $body = $response->getBody()->getContents();
        $data = json_decode($body, true);

        if (isset($data['errcode']) && $data['errcode'] != 0) {
            Log::debug("微信登录失败: ", $data);
            throw new \Exception("微信登录失败: " . $data['errmsg'] );
        }

        return $data;
    }
}